<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>Mypromise</div>
  <script>
    function Mypromise(fn){
      this.value;
      this.status = 'pending';
      this.resolveFn = function(){};
      this.rejectFn = function(){};
      fn(this.resolve.bind(this),this.reject.bind(this))
    }
    Mypromise.prototype.resolve = function(val){
      var self=this;
      if(self.status === 'pending'){
        self.status = 'resolved';
        self.value=val;
        setTimeout(function(){
          self.resolveFn(self.value)
        },0)
      }
    }
    Mypromise.prototype.reject = function(val){
      var self=this;
      if(self.status == 'pending') {
        self.status = 'rejected';
        self.value=val;
        setTimeout(function(){
          self.rejectFn(self.value)
        },0)
      }
    };
    Mypromise.prototype.then = function(resolveFn,rejectFn){
      var self = this;
      return new Mypromise(function(_resolve,_rejected){
          function resolveWrap(){
            var result = resolveFn(self.value);
            if (result && typeof result.then === 'function') {
              result.then(_resolve,_rejected);
            } else {
                _resolve(result);
            }
          };
          function rejectWrap(){
            var result = rejectFn(self.value);
            if (result && typeof result.then === 'function') {
              result.then(_resolve,_rejected);
            } else {
              _resolve(result)
            }
          };
          self.resolveFn = resolveWrap;
          self.rejectFn = rejectWrap;
      })
    };
    var fn=function(resolve, reject){
        console.log('1')
        resolve('less than 0.5');
        console.log('2')
        reject('greater than 0.5');
    };
    var p = new Mypromise(fn);
    p.then(function(data){
      console.log('resolve: ', data);
      return new Mypromise(function(resolve,reject){
        resolve('sde');
      })
    }, function(data){
      console.log('reject: ', data);
    })
    .then(function(res){
      console.log('222' + res)
    },function(rej){
      console.log(rej)
    })


  </script>
</body>
</html>
